<template>
  <div style="margin:50px 0;">
    <div>
      <h4>发表评论</h4>
      <hr />
      <van-cell-group>
        <van-cell class="van-field">
          <div class="van-field__body">
            <textarea
              v-model="textarea"
              placeholder="请输入留言"
              rows="1"
              class="van-field__control"
              style="height: 24px;"
            ></textarea>
          </div>
        </van-cell>
      </van-cell-group>
      <van-button @click="validationText" type="info">发表评论</van-button>
    </div>
    <van-list :finished="finished" finished-text="没有更多了">
      <van-cell v-for="(item, index) in commentsList" :key="index">
        <div class="title">
          <span>第{{index+1}}楼</span>
          <span>用户: {{item.user_name}}</span>
          <span>发表时间: {{item.add_time | dateFormat}}</span>
        </div>
        <div class="body">{{item.content}}</div>
      </van-cell>
    </van-list>
    <van-button @click="onLoadAll" plain hairline type="danger">加载更多</van-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 提交评论的内容
      textarea: "",
      finished: false,
      commentsList: [],
      testArr: [],
      pageindex: 1,
      id: ""
    };
  },
  created() {
    this.id = this.$route.query.id;
    this.onLoad();
  },
  methods: {
    async validationText() {
      if (this.textarea.length === 0) {
        this.$toast("留言不能为空");
        return;
      }
      const { data: res } = await this.$http.post(
        `/api/postcomment/${this.id}`,
        { content: this.textarea }
      );
      this.onLoad(false);
    },
    async onLoad(role) {
      if (role) {
        let { data: res } = await this.$http.get(`api/getcomments/${this.id}`, {
          params: { pageindex: this.pageindex }
        });
        if (res.status !== 0)
          return this.$notify({ type: "danger", message: "获取更多评论失败" });
        this.commentsList = this.commentsList.concat(res.message);
      } else {
        let { data: res } = await this.$http.get(`api/getcomments/${this.id}`, {
          params: { pageindex: 1 }
        });
        if (res.status !== 0)
          return this.$notify({ type: "danger", message: "获取更多评论失败" });
        this.commentsList = [];
        this.commentsList = res.message;
      }
    },
    onLoadAll() {
      this.pageindex++;
      this.onLoad(true);
    }
  }
};
</script>

<style lang="less" scoped>
.van-field {
  height: 100px;
  border: 1px solid #ccc;
}
.van-button {
  width: 100%;
  margin: 5px auto;
}
.title {
  height: 30px;
  background-color: #ccc;
  font-size: 12px;
  line-height: 30px;
}
.body {
  height: 35px;
  line-height: 35px;
  text-indent: 2em;
  font-size: 12px;
}
</style>